package com.woniuxy.Session;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * @auther linke
 * @create 2021-10-22 10:42
 * Session 会话
 *
 * session的作用域只存在一次会话之间
 */
@WebServlet("/sessionDemo03")
public class SessionDemo03 extends HttpServlet {
    /**
     * 设置session属性
     *  session的存活周期
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("sessionDemo03...执行了");
        //获取session对象
        HttpSession session = req.getSession();
        //向域中存储对象
        session.setAttribute("name","tom");
        //通过cookie设置session的存活周期

        Cookie cookie = new Cookie("JSESSIONID",session.getId());
       //cookie存活时长
        cookie.setMaxAge(60);
        //响应中添加cookie
        resp.addCookie(cookie);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
